package com.db.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import exam.common.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * @author Xiongx
 * @version 1.0
 * @date 2021/4/11 17:24
 * @since JDK 1.8
 */
@RestController
@Api(tags = {"数据库模块"})
public class DBTestController {

    private static final String devPATH=System.getProperty("user.dir");



    @GetMapping("dblist")
    @ApiOperation("获取备份的数据列表")
    public JSONObject getDbFileListController(){
        String filePath=devPATH+File.separator+"dbtemp";
        File file=new File(filePath);
        String[] str=file.list();
        return Result.successObject(str);
    }


    public void deleteOne() {
        String filePath=devPATH+File.separator+"dbtemp";
        File file=new File(filePath);
        String[] str=file.list();
        JSONArray jsonArray=new JSONArray();
        for (int i = 0; i < str.length; i++) {
            JSONObject jsonObject=new JSONObject();
            String fileName=str[i];
            jsonObject.put("file",filePath+File.separator+fileName);
            String s=str[i].replace("spring-demo","").replace(".sql","");
            SimpleDateFormat dft=new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
            try {
               Date date=dft.parse(s);
               jsonObject.put("time",date.getTime());
               System.out.println(date.getTime());
            }catch (Exception e){
                e.printStackTrace();
            }
            jsonArray.add(jsonObject);
        }
        List<JSONObject> list=JSONArray.parseArray(jsonArray.toJSONString(),JSONObject.class);
        Collections.sort(list, new Comparator<JSONObject>() {
            @Override
            public int compare(JSONObject o1, JSONObject o2) {
                long a = o1.getLongValue("time");
                long b = o2.getLong("time");
                if (a < b) {
                    return -1;
                } else if(a == b) {
                    return 0;
                } else
                    return 1;
            }
        });
        if(list.size()<10){
            return;
        }
        JSONObject jsonObject=list.get(0);
        String path=jsonObject.getString("file");
        File file1 = new File(path);
        if(file1.exists()){
            file1.delete();
        }
    }


    /**
     *
     *
     * @description:
     * @return:
     * @author: Xiongx
     * @time: 2021/4/13 14:42
     */
    @GetMapping("/dbtest")
    @ApiOperation("数据库备份模块")
    public JSONObject dbController(){
        String filePath=devPATH+File.separator+"dbtemp";
        String dbName="spring-demo";//备份的数据库名
        String username="root";//用户名
        String password="admin ";//密码
        File uploadDir = new File(filePath);
        SimpleDateFormat dft=new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
        String time=dft.format(new Date());
        if (!uploadDir.exists())
            uploadDir.mkdirs();
        String cmd =  "mysqldump -u "+ username +"  -p"+password +" "+ dbName + " -r "
                + filePath + "/" + dbName+time+ ".sql";
        try {
            Process process = Runtime.getRuntime().exec(cmd);
            System.out.println("备份数据库成功!!!");
            deleteOne();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return Result.successObject("备份成功");
    }
}
